/* eslint-disable @typescript-eslint/explicit-function-return-type */
import React, { useState, useEffect } from 'react'
import { Input, Button, Typography, Space, message, Card } from 'antd'
import {logger} from '../utils/logger'

const { Title, Text } = Typography

const OPCUAClientPanel: React.FC = () => {
  const [url, setUrl] = useState('opc.tcp://localhost:4840')
  const [nodeId, setNodeId] = useState('ns=1;s=Temperature')
  const [value, setValue] = useState<string | number | null>(null)
  const [connecting, setConnecting] = useState(false)

  const handleConnect = async () => {
    logger.verbose('尝试连接OPC UA服务器', { 
      endpoint: url, 
      nodeId ,
      state: 'initiating'
    });
    setConnecting(true)
    const result = await window.opcua.connect({ endpointUrl: url, nodeId })
    console.log(res);
    if (result.success) {
      message.success('Connected to OPC UA Server')
      logger.verbose('[OPCUA] 连接成功', { 
        endpoint: url,
        timestamp: new Date().toISOString() 
      });
    } else {
      logger.error('[OPCUA] 连接失败', new Error(result.message));
      message.error('Connection failed: ' + result.message)
      
    }

    setConnecting(false)
  }

  useEffect(() => {
    window.opcua.onOpcuaDataChanged((newValue) => {
      setValue(newValue)
    })
  }, [])

  return (
    <Card style={{ maxWidth: 600, margin: 'auto', marginTop: 40 }}>
      <Title level={4}>OPC UA Client</Title>
      <Space direction="vertical" size="middle" style={{ width: '100%' }}>
        <Input addonBefore="Endpoint" value={url} onChange={(e) => setUrl(e.target.value)} />
        <Input addonBefore="Node ID" value={nodeId} onChange={(e) => setNodeId(e.target.value)} />
        <Button type="primary" onClick={handleConnect} loading={connecting} block>
          Connect
        </Button>
        <div>
          <Text strong>Current Value:</Text> <Text code>{value !== null ? value : '--'}</Text>
        </div>
      </Space>
    </Card>
  )
}

export default OPCUAClientPanel
